package com.hjx.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> ss=new ThreadLocal<>();
    static {
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(boolean b){
        SqlSession sqlSession = ss.get();
        if (sqlSession==null){
            SqlSession s = sqlSessionFactory.openSession(b);
            ss.set(s);
            return s;
        }
        return sqlSession;
    }

    public static <T>T getMapper(Class<T> T,boolean b){
        SqlSession sqlSession = getSqlSession(b);
        T mapper = sqlSession.getMapper(T);
        return mapper;
    }
}
